﻿using DataModels.Models;
using DHISInteroperability.Authentication;
using DHISInteroperability.SystemInformation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ReportingManagement.Components.DHIS
{
    /// <summary>
    /// Interaction logic for DHISLogin.xaml
    /// </summary>
    public partial class DHISLogin : Window
    {
        private AuthorizationAgent agent;
        private bool dontAskAgain;
        private BackgroundWorker backgroundWorker;

        public DHISLogin()
        {
            InitializeComponent();
            loadingAnimation.Visibility = System.Windows.Visibility.Hidden;

            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += backgroundWorker_DoWork;
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
        }

        void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            loadingAnimation.Visibility = System.Windows.Visibility.Hidden;
            if (e.Error == null)
            {
                var info = e.Result as info;
                if (info != null)
                {
                    var infoBox = new DHISInfo(info);
                    infoBox.Owner = this;
                    infoBox.ShowDialog();

                    dontAskAgain = chboxDontAskAgain.IsChecked == null ? false : chboxDontAskAgain.IsChecked.Value;
                    this.DialogResult = true;
                    this.Close();
                    return;
                }
            }
            else
            {
                WebException webException = e.Error as WebException;
                bool messageShown = false;
                if (webException != null)
                {
                    if (webException.Status == WebExceptionStatus.ProtocolError)
                    {
                        MessageBox.Show(this, "Incorrect username or password");
                        messageShown = true;
                    }
                }
                
                if (!messageShown) MessageBox.Show(this, e.Error.Message);
            }

            // Restoring the buttons
            btnLogin.IsEnabled = true;
            btnCancel.IsEnabled = true;
            txtUsername.IsEnabled = true;
            txtPassword.IsEnabled = true;
            chboxDontAskAgain.IsEnabled = true;
        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] arguments = e.Argument as string[];
            string username = arguments[0];
            string password = arguments[1];
            string baseUrl = arguments[2];

            agent = new AuthorizationAgent(username, password);
            var system = new DHIS2System(baseUrl, agent);
            var info = system.GetInfo();
            e.Result = info;
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string username = txtUsername.Text;
            string password = txtPassword.Password;

            if (string.IsNullOrWhiteSpace(username) && string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show(this, "Username is required");
                txtUsername.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show(this, "Password is required");
                txtPassword.Focus();
                return;
            }

            btnLogin.IsEnabled = false;
            btnCancel.IsEnabled = false;
            txtUsername.IsEnabled = false;
            txtPassword.IsEnabled = false;
            chboxDontAskAgain.IsEnabled = false;
            loadingAnimation.Visibility = System.Windows.Visibility.Visible;
            
            var baseUrl = GenericTools.AppConfiguration.DHISBaseUrl;
            var arguments = new string[] { username, password, baseUrl };
            backgroundWorker.RunWorkerAsync(arguments);
        }

        /// <summary>
        /// Gets the Authorization Agent object set by the Login Form
        /// </summary>
        public AuthorizationAgent Agent
        {
            get { return agent; }
        }

        /// <summary>
        /// Indicates whether for the next request user should be asked for DHIS credentials
        /// </summary>
        public bool DontAskAgain
        {
            get { return dontAskAgain; }
        }
    }
}
